package edu.gyc.testthread;

public class Demo7 {

    public static void main(String[] args) {
        final Printer p = new Printer();
        new Thread() {
            public void run() {
                while (true) {
                    try {
                        p.print1();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        new Thread() {
            public void run() {
                while (true) {
                    try {
                        p.print2();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
}

class Printer {
    private int flag = 1;

    public void print1() throws InterruptedException {
        synchronized (this) {
            while (flag != 1) {
                this.wait();//当前线程等待
            }
            System.out.print("A");
            System.out.print("B");
            System.out.print("C");
            System.out.print("D");
            System.out.print("E");
            System.out.print("\r\n");
            flag = 2;
            this.notify();//随机唤醒单个等待的线程
        }
    }

    public void print2() throws InterruptedException {
        synchronized (this) {
            while (flag != 2) {
                this.wait();
            }
            System.out.print("伟");
            System.out.print("大");
            System.out.print("的");
            System.out.print("Java");
            System.out.print("\r\n");
            flag = 1;
            this.notify();
        }
    }
}
